package ru.mti.edu.servlet;

import static ru.mti.edu.servlet.Constant.*;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RedirectServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp){
		
		try {
			HttpSession session = req.getSession();
			Boolean isAuth = (Boolean) session.getAttribute(IS_AUTH_SESSION_ATTRIBUTE_NAME);
			if (Boolean.TRUE.equals(isAuth)){
				resp.sendRedirect("successLogin.html");
			}
			else {
				Cookie[] cookies = req.getCookies();
				if (cookies != null){
					for (Cookie cookie : cookies){
						if (cookie.getName().equalsIgnoreCase(LAST_LOGIN_COOKIE_NAME)){
							String cookieValue = cookie.getValue();
							if (cookieValue.equalsIgnoreCase("SCOTT")){
								resp.sendRedirect("scottPage.html");
								return;
							}
						}
					}
				}
				resp.sendRedirect("login.html");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
